package Thread;

public class Demo17 {
    /**
     * 在这个main中t1和t2 约定好加锁顺序，先加locker1再加locker2，就能避免死锁的情况
     * 这个方法是再了解死锁构成的4个条件之一：循环等待
     * 不让循环等待，我们事先约定好加锁的顺序，就能避免死锁的情况
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
        Object locker1 = new Object();
        Object locker2 = new Object();
        Thread t1 = new Thread(()->{
            synchronized (locker1){
                //星拿起酱油
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (locker2){
                    //尝试拿起醋
                    System.out.println("t1线程获取到两把锁");
                }
            }
        });
        Thread t2 = new Thread(()->{
            synchronized (locker1){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (locker2){
                    System.out.println("t2线程获取两把锁");
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }

    public static void main1(String[] args) throws InterruptedException {
     Object locker1 = new Object();
     Object locker2 = new Object();
     Thread t1 = new Thread(()->{
         synchronized (locker1){
             //星拿起酱油
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 throw new RuntimeException(e);
             }
             synchronized (locker2){
                 //尝试拿起醋
                 System.out.println("t1线程获取到两把锁");
             }
         }
     });
     Thread t2 = new Thread(()->{
         synchronized (locker2){
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 throw new RuntimeException(e);
             }
             synchronized (locker1){
                 System.out.println("t2线程获取两把锁");
             }
         }
     });
     t1.start();
     t2.start();
     t1.join();
     t2.join();
    }
}
